// ignore_for_file: non_constant_identifier_names, constant_identifier_names

import 'dart:convert';
import 'package:http/http.dart' as http;

const String URL = 'https://api.heclouds.com/devices/';
const String ID = '911825502';
const String APIKEY = 'wOpnE2167jHbM22zqRWrvvN0=zM=';
const String DSID = 'temp_cpu';

// ignore: deprecated_member_use
late List<DBDataNodeModel> DataNode = [
  DBDataNodeModel(0, '0'),
  DBDataNodeModel(1, '1'),
];

class Device {
  late String device_id;
  late String api_key;
  late String dsid;
  // const
  static const String QHD = '/datapoints'; // Query History Data

  Device({this.device_id = ID, this.api_key = APIKEY, this.dsid = DSID});

  get({int limit = 100}) async {
    var url = Uri.parse(URL + device_id + QHD + '?datastream_id=$dsid&limit=$limit');
    var response = await http.get(url, headers: {'api-key': api_key});
    var data = jsonDecode(response.body);
    int count = data['data']['count'];
    // log(data['err']);
    if ((data['errno'] == 0) & (count > 0)) {
      var datapoints = data['data']['datastreams'][0]['datapoints'];
      parse(count, datapoints);
      return true;
    }
    return false;
  }

  real_update() async {
    var url = Uri.parse(URL + device_id + QHD + '?datastream_id=$dsid');
    var response = await http.get(url, headers: {'api-key': api_key});
    var data = jsonDecode(response.body);
    int count = data['data']['count'];
    if ((data['errno'] == 0) & (count > 0)) {
      var datapoints = data['data']['datastreams'][0]['datapoints'];
      String at = datapoints[0]['at'].split(' ')[1].substring(0, 8);
      double value = datapoints[0]['value'];
      if (at != DataNode[DataNode.length - 1].name) {
        DataNode.removeAt(0);
        DataNode.add(DBDataNodeModel(value, at));
      }
      return true;
    }
    return false;
  }

  parse(count, datapoints) {
    DataNode = [];
    for (var i = count - 1; i >= 0; i--) {
      // log(datapoints[i].toString());
      String at = datapoints[i]['at'].split(' ')[1].substring(0, 8);
      double value = datapoints[i]['value'];
      // print(at + ' -> ' + value.toString());
      DataNode.add(DBDataNodeModel(value, at));
    }
  }
}

class DBDataNodeModel {
  final String name;
  final double value;
  DBDataNodeModel(this.value, this.name);

  @override
  String toString() {
    return {'name': name, 'value': value}.toString();
  }
}

final Device dev = Device(); // 公用
